<?php

namespace y\controllers;

use Yii;
use yii\web\Controller;
use yii\helpers\Json;

class SiteController extends BaseController
{

    // 盒追溯
    public function actionIndex()
    {
        $id = Yii::$app->request->get('id');
        $batch = substr($id, 0, 10);
        $id2 = $batch . ' '. substr($id, 10);
        $row = Yii::$app->db_yisu->createCommand("SELECT * FROM ebcproductioncode WHERE Id in ('{$id}', '{$id2}')")->queryOne();
        $product_date = '';
        $valid_date = '';
        $send_date = '';
        $is_new_comp = 0;   // 新公司
        if (!empty($row)) {
            $valid_date = date('Y-m-d', strtotime(substr($row['ValidDate'], 0, 10)) - 86400);
            $product_date = substr($row['PackDate'], 0, 10);

            $bill = Yii::$app->db_yisu->createCommand("SELECT HeaderId FROM ebtBillData WHERE ProductionCodeId='{$id}'")->queryOne();
            if (!empty($bill)) {
                $headerId = $bill['HeaderId'];
                $bill_header = Yii::$app->db_yisu->createCommand("SELECT AddTime FROM ebtBillHeader WHERE Id='{$headerId}'")->queryOne();
                if (!empty($bill_header)) {
                    $send_date = substr($bill_header['AddTime'], 0, 10);
                }
            }
            if (substr($row['AddTime'], 0, 10) > '2022-03-28') {
                $is_new_comp = 1;
            }
        } else{
            if (substr($id, 0, 6) > 220328) {
                $is_new_comp = 1;
            }
            $product_date = substr($batch, 0, 2) . '-' . substr($batch, 2, 2) . '-' . substr($batch, 4, 2);
            $product_date = date('Y-m-d', strtotime("$product_date +2 days"));
            $valid_date = date('Y-m-d', strtotime("$product_date +18 months") - 86400);
        }
        if (empty($send_date)) {
            // $send_date = date('Y-m-d', strtotime("$product_date +6 days"));
        }
        if (in_array($id, ['210512239A072380','210512239A072381', '210512239A072382', '210512239A072383','210512239A072384', '210512239A072385', '210512239A072386','210512239A072387', '210512239A072388', '210512239A072389','210804262A001000', '210804262A001001', '210804262A001002','210804262A001003', '210804262A001004', '210804262A001005','210804262A001006', '210804262A001007', '210804262A001008','210804262A001009', '210804262A001010', '210804262A001011', '210820270A008366', '210820270A008367', '210820270A008368', '210820270A008369', '210820270A008370', '210820270A008371', '210820270A008372', '210820270A008373', '210820270A008374', '210820270A008375', '210820270A008376', '210820270A008377', '210820270A008378'])) {
            $send_date = '2021-10-20';
        }

        in_array($id, ['220217270A000024', '220217270A000027','220217270A000029','220217270A000032']) && $is_new_comp = 1;
        
        if ($batch=='220217270A' && $is_new_comp != 1) {
            $box_no = substr($id, -6);
            $box_no >=485 && $box_no <= 541 && $is_new_comp = 1;
        }

        $product_type = 0;
        if (stripos($batch, '82A'))     $product_type = 1;
        elseif (stripos($batch, '83A')) $product_type = 2;
        elseif (stripos($batch, '84A')) $product_type = 3;
        elseif($batch == '220512271A')  $product_type = 4;
        elseif (stripos($batch, '89A')) $product_type = 5;
        elseif (stripos($batch, '90A')) $product_type = 6;

        if ($product_type == 4) {
            $product_date = "2022-05-12";
            $is_new_comp = 0;
        } elseif ($product_type == 5 || $product_type == 6) {
//            $product_date = "2023-09-08";
//            $send_date = "2023-09-08";
//            $valid_date = "2025-03-07";
        }

        if ($batch=='220604282A') {
            $product_date = "2022-06-13";
            $send_date = "2022-06-29";
        } elseif ($batch=='220614285A') {
            $product_date = "2022-06-27";
            $send_date = "2022-06-29";
        }
        return $this->fetch([
            'id' => $id,
            'product_name' => Yii::$app->params['products'][$product_type],
            'product_type' => $product_type,
            'batch' => $batch,
            'product_date' => $product_date,
            'valid_date' => $valid_date,
            'send_date' => $send_date,
            'is_new_comp' => $is_new_comp,
        ]);
    }

    public function actionBox2()
    {
        $id = Yii::$app->request->get('id');
        $box = Yii::$app->db->createCommand("SELECT * FROM virtual_box_qrcode WHERE box_no='{$id}'")->queryOne();
        $batch = $box['batch'];
        $send_date = date('Y-m-d', $box['send_at']);
        $product_date = date('Y-m-d', $box['product_at']);
        $valid_date = date('Y-m-d', strtotime("+18 months", $box['product_at']) - 86400);
        return $this->render('box', [
            'id' => $id,
            'batch' => $batch,
            'product_date' => $product_date,
            'valid_date' => $valid_date,
            'send_date' => $send_date,
        ]);
    }

    // 箱追溯
    public function actionBox()
    {
        $id = Yii::$app->request->get('id');
        $batch = substr($id, 8, 10);

        $product_type = 0;
        if (stripos($batch, '82A')) {
            $product_type = 1;
        } elseif (stripos($batch, '83A')) {
            $product_type = 2;
        } elseif (stripos($batch, '84A')) {
            $product_type = 3;
        }
        $product_name = Yii::$app->params['products'][$product_type];
        
        $product_date = substr($id, 0, 4).'-'.substr($id, 4, 2).'-'.substr($id, 6, 2);
        $valid_date = date('Y-m-d', strtotime('18 months', strtotime($product_date) - 86400));
        $send_date = '';
        $row = Yii::$app->db_yisu->createCommand("SELECT * FROM ebcproductioncode WHERE CodeLevel=1 AND BatchCode='{$batch}' AND ParentCode LIKE '{$id}%' AND AddTime > '2021-11-17 04:12:45'")->queryOne();
        $is_new_comp = 0;
        if (!empty($row)) {
            $bill = Yii::$app->db_yisu->createCommand("SELECT HeaderId FROM ebtBillData WHERE ProductionCodeId='{$row['Id']}'")->queryOne();
            if (!empty($bill)) {
                $headerId = $bill['HeaderId'];
                $bill_header = Yii::$app->db_yisu->createCommand("SELECT AddTime FROM ebtBillHeader WHERE Id='{$headerId}'")->queryOne();
                if (!empty($bill_header)) {
                    $send_date = substr($bill_header['AddTime'], 0, 10);
                }
            }
            if (substr($row['AddTime'], 0, 10) > '2022-03-28') {
                $is_new_comp = 1;
            }
        } else {
            if (substr($id, 0, 8) > 20220328) {
                $is_new_comp = 1;
            }
        }

        if($batch == '220512271A') {
            $is_new_comp = 0;
        }
        return $this->render('box', [
            'id' => $id,
            'batch' => $batch,
            'product_name' => $product_name,
            'product_type' => $product_type,
            'product_date' => $product_date,
            'valid_date' => $valid_date,
            'send_date' => $send_date,
            'is_new_comp' => $is_new_comp,
        ]);
    }

    // 贵州追溯
    public function actionGzzs()
    {
        $id = Yii::$app->request->get('yyb_code');
        $row = Yii::$app->db_yisu->createCommand("SELECT * FROM ebcproductioncode WHERE Id LIKE '{$id}%' AND CodeLevel in (1,2) AND AddTime > '2021-11-17 04:12:45'")->queryOne();
        if (empty($row)) {
            exit(Json::encode(['code' => 1, 'msg' => '编码错误']));
        }
        $result = [
            'code' => 0,
            'msg' => 'ok',
            'manuFacturer' => '天添爱（青岛）生物科技有限公司苏州分公司',
            'nutrientName' => Yii::$app->params['products'][0],
            'dateInProduced' => '',
            'effectiveDate' => '',
            'releaseDate' => '',
            'batchNumber' => '',
            'trunkNumber' => '',
            'reportUrls' => [],
            'boxsNumber' => [],
        ];
        if ($row['CodeLevel'] == 1) {
            $result['dateInProduced'] = substr($row['PackDate'], 0, 10);
            $result['batchNumber'] = substr($id, 0, 10);
            $result['boxsNumber'][] = $id;

            $bill = Yii::$app->db_yisu->createCommand("SELECT HeaderId FROM ebtBillData WHERE ProductionCodeId='{$id}'")->queryOne();
        } else {
            $result['trunkNumber'] = $id;
            $result['batchNumber'] = substr($id, 8, 10);
            $result['dateInProduced'] = substr($id, 0, 4).'-'.substr($id, 4, 2).'-'.substr($id, 6, 2);
            $childs = Yii::$app->db_yisu->createCommand("SELECT Id FROM ebcproductioncode WHERE ParentCode like '{$id}%' AND CodeLevel=1 AND AddTime > '2021-11-17 04:12:45'")->queryAll();
            if (!empty($childs)) {
                $bill = Yii::$app->db_yisu->createCommand("SELECT HeaderId FROM ebtBillData WHERE ProductionCodeId='{$childs[0]['Id']}'")->queryOne();
                $result['boxsNumber'] = array_column($childs, "Id");
            }
        }
        if (!empty($bill)) {
            $headerId = $bill['HeaderId'];
            $bill_header = Yii::$app->db_yisu->createCommand("SELECT AddTime FROM ebtBillHeader WHERE Id='{$headerId}'")->queryOne();
            if (!empty($bill_header)) {
                $result['releaseDate'] = substr($bill_header['AddTime'], 0, 10);
            }
        }
        if (empty($result['releaseDate']) && $result['batchNumber'] == '220523239A') {
            $result['releaseDate'] = '2022-06-04';
        }
        $result['effectiveDate'] = date('Y-m-d', strtotime("+18 months", strtotime($result['dateInProduced'])) - 86400);

        $report = Yii::$app->db_yisu->createCommand("SELECT * FROM ebcProductQcRecord WHERE BatchCode='{$result['batchNumber']}'")->queryOne();
        if (!empty($report['ProdInspectionReport'])) {
            $result['reportUrls'][] = 'http://103.156.68.126:9001/ProductQcFile_upload/' . $report['ProdInspectionReport'];
        }
        exit(Json::encode($result));
    }

    public function actionZjbg()
    {
        $batch = Yii::$app->request->get('batch');
        $row = Yii::$app->db_yisu->createCommand("SELECT * FROM ebcProductQcRecord WHERE BatchCode='{$batch}'")->queryOne();
        $row || exit('暂无查询结果');

        header('Location:' . 'http://103.156.68.126:9001/ProductQcFile_upload/' . $row['ProdInspectionReport']);
    }

    public function actionExtra()
    {
        return $this->fetch([
            'show' => Yii::$app->request->get('show'),
        ]);
    }

    // 云南：二维码追溯信息查询
    public function actionYnzs()
    {
        $id = Yii::$app->request->get('code');
        $row = Yii::$app->db_yisu->createCommand("SELECT * FROM ebcproductioncode WHERE Id='{$id}' AND CodeLevel=1")->queryOne();
        if (empty($row)) {
            if (strlen($id) != 16 || substr($id, 0, 2) < 21 || substr($id, 0, 6) > date('ymd') || !preg_match("/^[0-9]{9}A[0-9]{6}$/", $id)) {
                exit(Json::encode(['code' => 404, 'errMsg' => '码不存在', 'data' => null]));
            }
            $batch = substr($id, 0, 10);
            $product_date = '20' . substr($batch, 0, 2) . '-' . substr($batch, 2, 2) . '-' . substr($batch, 4, 2);
            $valid_date = date('Y-m-d', strtotime('+18 months', strtotime($product_date)));
            $date = date('Y-m-d');
            $sql = "INSERT INTO ebcproductioncode(Id,AddBy,AddTime,EditBy,EditTime,BatchCode,CodeLevel,CodePath,Count,FactoryId,IsRunning,LineId,MaterialId,MinSaleUnit,PackDate,ParentCode,PrintDate,RootCode,Sequence,ShouldOrgId,ShouldOrgType,ValidDate)
VALUES
('{$id}','hpp1','{$date} 08:00:00.000','hpp1','{$date} 08:00:00.000','{$batch}',1,'9,99',1,'9e0c70cc-a631-4408-8daf-529cbb629e95',0,1,'24ba45d9-c51e-44ec-83d2-89cf840c815e',1,'{$product_date} 00:00:00.000','9','{$product_date} 00:00:00.000','99',1,'a55a3fb6-7a4a-4a03-88ed-79390c9fae3c',3,'{$valid_date} 00:00:00.000');";
            Yii::$app->db_yisu2->createCommand($sql)->execute();
        } else {
            $product_date = substr($row['PackDate'], 0, 10);
            $batch = substr($id, 0, 10);
        }
        exit(Json::encode(['code' => 0, 'errMsg' => '', 'data' => [
            'produceDate'   => $product_date,
            'batchNumber'   => $batch,
            'productSpecs'  => '12g/袋*30袋/盒*30盒/箱',
            'validityMonth' => 18,
        ]]));
    }

    // 云南：二维码不存在或者重复生成新的
    public function actionYnew()
    {
        $code = Yii::$app->request->get('code');
        if (strlen($code) != 16 || substr($code, 0, 2) < 21 || substr($code, 0, 6) > date('ymd') || !preg_match("/^[0-9]{9}A[0-9]{6}$/", $code)) {
            exit(Json::encode(['code' => 404, 'errMsg' => '码不正确', 'data' => null]));
        }
        $exists = Yii::$app->db->createCommand("SELECT * FROM zs_np_code WHERE old_code='{$code}%' order by id desc")->queryOne();
        $batch = substr($code, 0, 10);
        $last = Yii::$app->db->createCommand("SELECT * FROM zs_np_code WHERE code like '{$batch}%' order by id desc")->queryOne();
        if ($last) {
            $newCode = substr($last['code'], 0, 10) . (substr($last['code'], 10) + 1);
        } else {
            $newCode = $batch . '900001';
        }
        Yii::$app->db->createCommand()->insert('zs_np_code', [
            'code' => $newCode,
            'old_code' => $code,
            'created_at' => time(),
        ])->execute();
        exit(Json::encode(['code' => 0, 'errMsg' => '', 'data' => [
            'code' => $newCode,
            'old_code' => $code,
        ]]));
    }


}
